//
//  SchemeCenterCtrl.m
//  cutter
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "SchemeProductList.h"
#import "UserCenterPick.h"
#import "SchemeSelector.h"
#import "SchemeCenterCtrl.h"
#import "MatchDetailCtrl.h"
#import "ProductDetailCtrl.h"
#import "ProductCenterCtrl.h"
#import "SpaceEditController.h"
#import "OtherCustom.h"
#import "SWTableViewCell.h"

//
#pragma mark -
#pragma mark SchemeListsCtrl
@interface SchemeListCtrlCell : SWTableViewCell
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *clientView;
@end
@implementation SchemeListCtrlCell
@end
@implementation SchemeListCtrl
- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(globalValueChange:) name:@"globalValueChange" object:nil];
    [self.view setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.3]];
    [self.rightLayout setConstant:-334];
    [self.view updateConstraintsIfNeeded];
    [self.view setAlpha:0];
    self.button1.selected = YES;
    //
    if ([TMGlobal valueForKey:@"client"]) {
        [self buttonTouch:self.button1];
    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)globalValueChange:(NSNotification *)info{
    if ([info.object isEqualToString:@"client"]) {
        if ([TMGlobal valueForKey:@"client"]) {
            [self buttonTouch:self.button1];
        }
    }
}
-(void)reloadData{
    if ([TMGlobal valueForKey:@"client"]) {
        [self buttonTouch:self.button1];
    }else{
        self.tipsView.hidden = YES;
        self.tableView.hidden = NO;
        [self.condition setValue:nil forKey:@"clientid"];
        [self setData:[AppData userScheme:self.condition]];
        [self.tableView reloadData];
    }
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
        [self.condition setValue:@(0) forKey:@"isshare"];
        [self.condition setValue:@(10000) forKey:@"limit"];
        [self.condition setValue:@(1) forKey:@"page"];
    }
    return _condition;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //
    
    //
    __weak SchemeListCtrl *blockSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view setAlpha:1];
    } completion:^(BOOL finished) {
        [blockSelf.rightLayout setConstant:0];
        [blockSelf.view updateConstraintsIfNeeded];
        [UIView animateWithDuration:0.2 animations:^{
            [blockSelf.view layoutIfNeeded];
        } completion:^(BOOL finished) {
        }];
    }];
}
-(IBAction)buttonTouch:(UIButton *)sender{
    self.button1.selected = NO;
    self.button2.selected = NO;
    sender.selected = YES;
    //
    if(sender == self.button1){
        if ([TMGlobal valueForKey:@"client"]) {
            self.tipsView.hidden = YES;
            self.tableView.hidden = NO;
            NSString *name = [[TMGlobal valueForKey:@"client"] objectForKey:@"truename"];
            [self.button1 setTitle:name forState:UIControlStateNormal];
            [self.button1 setTitle:name forState:UIControlStateSelected];
            //
            [self.condition setValue:[[TMGlobal valueForKey:@"client"] objectForKey:@"uuid"] forKey:@"clientuuid"];
            [self setData:[AppData userScheme:self.condition]];
            [self.tableView reloadData];
            
        }else{
            self.tipsView.hidden = NO;
            self.tableView.hidden = YES;
        }
    }
    if(sender == self.button2){
        self.tipsView.hidden = YES;
        self.tableView.hidden = NO;
        [self.condition setValue:nil forKey:@"clientid"];
        [self.condition setValue:nil forKey:@"clientuuid"];
        [self setData:[AppData userScheme:self.condition]];
        [self.tableView reloadData];
    }
    //
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([[touches anyObject] view] == self.view) {
        [self.rightLayout setConstant:-334];
        [self.view updateConstraintsIfNeeded];
        //
        __weak SchemeListCtrl *blockSelf = self;
        [UIView animateWithDuration:0.2 animations:^{
            [blockSelf.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                [blockSelf.view setAlpha:0];
            } completion:^(BOOL finished) {
                [blockSelf dismissViewControllerAnimated:NO completion:nil];
            }];
        }];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *item = [self.data objectAtIndex:indexPath.row];
    SchemeListCtrlCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    if([item objectForKey:@"client"] != [NSNull null]){
        [cell.clientView setText:[AppData objToString:[item objectForKey:@"truename"] lable:nil]];
    }else{
        [cell.clientView setText:@""];
    }
    [cell.nameView setText:[AppData objToString:[item objectForKey:@"schemename"] lable:nil]];
    
    //
    [cell setRightUtilityButtons:[self rightButtons] WithButtonWidth:80.0f];
    cell.delegate = self;
    //
    return cell;
}
- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0]
                                                title:@"修改"];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"Delete"];
    
    return rightUtilityButtons;
}
- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state{
    switch (state) {
        case 1:
            return NO;
            break;
        case 2:
            return YES;
            break;
        default:
            break;
    }
    return YES;
}
- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
    return YES;
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            //            __weak SchemeListCtrl *this = self;
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"SchemeCenter" bundle:nil];
            UINavigationController *ctrl =[story instantiateViewControllerWithIdentifier:@"SchemeEdit"];
            //
            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
            id item = [self.data objectAtIndex:cellIndexPath.row];
            //
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:item forKey:@"scheme"];
            [TMGlobal setValue:dic forKey:@"dic"];
            
            ctrl.modalPresentationStyle = UIModalPresentationFormSheet;
            [self presentViewController:ctrl animated:YES completion:nil];
            
            //            NSLog(@"%@",ctrl);
            //            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            
            __weak SchemeCenterEdit *root =[ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [AppData userEditScheme:result bitmap:nil];
                [self.button2 sendActionsForControlEvents:UIControlEventTouchUpInside];
                [root dismissViewControllerAnimated:YES completion:nil];
            }];
            
            
            //            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
            //            id dat =[self.data objectAtIndex:cellIndexPath.row];
            //            [[NSNotificationCenter defaultCenter]postNotificationName:@"didSelectSchemeListCtrlCell" object:dat];
            break;
        }
        case 1:
        {
            NSLog(@"123456");
            //
            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
            id item = [self.data objectAtIndex:cellIndexPath.row];
            [AppData userDeleteScheme:item];
            [self.tableView reloadData];
            [self.button2 sendActionsForControlEvents:UIControlEventTouchUpInside];
            
            break;
        }
        default:
            break;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    id dat =[self.data objectAtIndex:indexPath.row];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"didSelectSchemeListCtrlCell" object:dat];
}
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//    return YES;
//}
//
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        id item = [self.data objectAtIndex:indexPath.row];
//        [AppData userDeleteScheme:item];
//        [self reloadData];
//    }
//}
//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                if(result){
                    [self.tableView reloadData];
                }
                [ctrl dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }
}
@end


//
@interface SchemeCenterAddCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UITextField *nameView;
@property (weak, nonatomic) IBOutlet UILabel *countView;
@property (weak, nonatomic) IBOutlet UIButton *subView;
@property (weak, nonatomic) IBOutlet UIButton *addView;
@property (strong, nonatomic) id data;
@end
@implementation SchemeCenterAddCell
- (void)awakeFromNib{
    [super awakeFromNib];
    if ([self.reuseIdentifier isEqualToString:@"cellIdentifier"]) {
        [self.addView addTarget:self action:@selector(countTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.subView addTarget:self action:@selector(countTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self setCount:[[self.data objectForKey:@"count"] integerValue]];
    }
}
- (void)countTouch:(id)sender{
    NSInteger count = [[self.data objectForKey:@"count"] integerValue];
    if (self.addView == sender) {
        [self setCount:count + 1];
    }else{
        [self setCount:count - 1];
    }
}
- (void)setCount:(NSInteger)count{
    [self.data setValue:[NSNumber numberWithInteger:count] forKey:@"count"];
    NSString *text = [NSString stringWithFormat:@"%@",[self.data valueForKey:@"count"]];
    [self.countView setText:text];
    //
    if (count > 0) {
        [self.countView setHidden:NO];
        [self.subView setHidden:NO];
    }else{
        [self.countView setHidden:YES];
        [self.subView setHidden:YES];
    }
}
@end


@implementation SchemeCenterEdit
- (void)viewDidLoad{
    [super viewDidLoad];
    self.source = [NSMutableDictionary dictionary];
    self.source =[TMGlobal valueForKey:@"dic"];
    id schemename = [[self.source objectForKey:@"scheme"] objectForKey:@"schemename"];
    id truename = [[self.source objectForKey:@"scheme"] objectForKey:@"truename"];
    NSLog(@"%@%@",schemename,truename);
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 1;
    }
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        SchemeCenterAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
        [cell.nameView setText:[[self.source objectForKey:@"scheme"] objectForKey:@"schemename"]];
        //        NSLog(@"===%@",[[self.source objectForKey:@"scheme"] objectForKey:@"schemename"]);
        //        cell.nameView = [[self.source objectForKey:@"scheme"] objectForKey:@"schemename"];
        [self setNameView:cell.nameView];
        return cell;
    }
    SchemeCenterAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userIdentifier"];
    if (self.source) {
        [cell.nameView setText:[[self.source objectForKey:@"scheme"] objectForKey:@"truename"]];
    }
    return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UserCenterPick.class]) {
        __weak SchemeCenterEdit *this = self;
        //
        UserCenterPick *ctrl = segue.destinationViewController;
        [ctrl setOnSelected:^(id target, id result){
            [this setClient:result];
            //
            [[this.source objectForKey:@"scheme"] setValue:[this.client objectForKey:@"truename"] forKey:@"truename"];
            [[this.source objectForKey:@"scheme"] setValue:[this.client objectForKey:@"uuid"] forKey:@"clientuuid"];
            [[this.source objectForKey:@"scheme"] setValue:[this.client objectForKey:@"id"] forKey:@"clientid"];
            [this.tableView reloadData];
            //
            [this.navigationController popToRootViewControllerAnimated:YES];
            [this.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [ctrl setClient:self.client];
        [ctrl setSetCurrent:NO];
    }
}
- (IBAction)exitTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (IBAction)buildTouch:(id)sender {
    if ([self.nameView.text length] == 0) {
        [UIAlertController show:nil message:@"方案名称不能为空!" buttons:nil handler:nil];
    }else{
        id item =[self.source objectForKey:@"scheme"];
        //id json = [item objectForKey:@"json"];
        NSMutableDictionary *datas = [NSMutableDictionary dictionary];
        [datas setValue:[item objectForKey:@"clientuuid"] forKey:@"clientuuid"];
        [datas setValue:[item objectForKey:@"clientid"] forKey:@"clientid"];
        //
        [datas setValue:[item objectForKey:@"uuid"] forKey:@"uuid"];
        [datas setValue:[item objectForKey:@"id"] forKey:@"id"];
        [datas setValue:self.nameView.text forKey:@"schemename"];
        //        [datas setValue:json forKey:@"json"];
        
        //
        
        self.onSelected(self, datas);
    }
}
@end

//
@implementation SchemeCenterAdd
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    if (self.append) {
        [self setTitle:@"添加房间"];
        [self.navigationItem.rightBarButtonItem setTitle:@"添加"];
    }else{
        [self setTitle:@"新方案"];
        [self.navigationItem.rightBarButtonItem setTitle:@"创建"];
    }
    //
    __weak SchemeCenterAdd *this = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this setData:[AppData userSchemeSpace:nil]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:this.view animated:YES];
            [this.tableView reloadData];
        });
    });
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.append == NO) {
        if (self.client == nil) {
            [self setClient:[TMGlobal valueForKey:@"client"]];
        }
        return 3;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.append == NO) {
        if (section == 0 || section == 1) {
            return 1;
        }
    }
    return [self.data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.append == NO) {
        if (indexPath.section == 0) {
            SchemeCenterAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
            [self setNameView:cell.nameView];
            return cell;
        }
        if (indexPath.section == 1) {
            SchemeCenterAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userIdentifier"];
            if (self.client) {
                [cell.nameView setText:[self.client objectForKey:@"truename"]];
            }
            return cell;
        }
    }
    //
    NSMutableDictionary *item = [self.data objectAtIndex:indexPath.row];
    SchemeCenterAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.iconView];
    [cell.nameView setText:[item objectForKey:@"classname"]];
    [cell setData:item];
    return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UserCenterPick.class]) {
        __weak SchemeCenterAdd *this = self;
        UserCenterPick *ctrl = segue.destinationViewController;
        [ctrl setClient:self.client];
        [ctrl setOnSelected:^(id target, id result){
            [this setClient:result];
            //
            [this.navigationController popToRootViewControllerAnimated:YES];
            [this.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.append == NO) {
        if (section == 2) {
            return @"空间";
        }
        if (section == 1) {
            return @"属于客户";
        }
    }
    return nil;
}
//
- (IBAction)exitTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }else{
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}
- (IBAction)buildTouch:(id)sender {
    if (self.onSelected) {
        NSMutableArray *json = [NSMutableArray array];
        for (id item in self.data) {
            NSInteger count = [[item objectForKey:@"count"] integerValue];
            for (NSInteger i=0; i<count; i++) {
                NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
                [tmp setValue:[item objectForKey:@"classname"] forKey:@"space"];
                [tmp setValue:[item objectForKey:@"pic"] forKey:@"icon"];
                [tmp setValue:[item objectForKey:@"id"] forKey:@"id"];
                [json addObject:tmp];
            }
        }
        if (self.append) {
            self.onSelected(self, json);
        }else{
            if ([self.nameView.text length] == 0) {
                [UIAlertController show:nil message:@"方案名称不能为空!" buttons:nil handler:nil];
            }else{
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setValue:[self.client objectForKey:@"uuid"] forKey:@"clientuuid"];
                [data setValue:[self.client objectForKey:@"id"] forKey:@"clientid"];
                [data setValue:self.nameView.text forKey:@"schemename"];
                [data setValue:self.client forKey:@"client"];
                [data setValue:json forKey:@"json"];
                //
                self.onSelected(self, data);
            }
        }
    }else{
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}
@end


//
#pragma mark -
#pragma mark SchemeCenterList
@implementation SchemeCenterList
-(void)viewDidLoad{
    [super viewDidLoad];
    //
    [self.deleteView setHidden:YES];
    [self.deleteView addTarget:self action:@selector(deleteTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.editView addTarget:self action:@selector(editTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView setAllowsMultipleSelection:YES];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.searchView setDelegate:self];
    [self headerRefresh:nil];
}
//
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.condition setValue:textField.text forKey:@"keyword"];
    [self.condition setValue:@(1) forKey:@"page"];
    [self headerRefresh:nil];
    return YES;
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak SchemeCenterList *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userScheme:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.collectionView.footerView setFinish:NO];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak SchemeCenterList *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userScheme:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:[NSNumber numberWithBool:NO] forKey:@"isshare"];
    [_condition setValue:@(50) forKey:@"limit"];
    return _condition;
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count]+1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        SchemeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addIdentifier" forIndexPath:indexPath];
        return cell;
    }
    NSDictionary *item = [self.data objectAtIndex:indexPath.item-1];
    SchemeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"schemename"] lable:nil]];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [cell.selectView setHidden:self.deleteView.hidden];
    return cell;
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    return self.deleteView.hidden;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak SchemeCenterList *this = self;
    if ([segue.destinationViewController isKindOfClass:SchemeCenterCtrl.class]) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath) {
            SchemeCenterCtrl *ctrl = segue.destinationViewController;
            if (indexPath.item > 0) {
                [ctrl import:[self.data objectAtIndex:indexPath.item - 1]];
            }
            [ctrl setOnSelected:^(id target, id result){
                [this headerRefresh:nil];
                [this dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }
}
//
- (void)editTouch:(UIButton*)sender{
    [sender setSelected:!sender.selected];
    [self.deleteView setHidden:!sender.selected];
    //
    NSArray *cells = [self.collectionView visibleCells];
    for (SchemeCenterCell *cell in cells) {
        if ([cell isKindOfClass:SchemeCenterCell.class]) {
            [cell.selectView setHidden:!sender.selected];
        }
    }
}
- (void)deleteTouch:(UIButton*)sender{
    __weak typeof(self) this = self;
    [UIAlertController showAt:self title:nil message:@"删除选中的方案？" buttons:@[@"删除",@"取消"] handler:^(UIAlertAction *action) {
        if ([action.title isEqualToString:@"删除"]) {
            NSArray *indexPaths = [this.collectionView indexPathsForSelectedItems];
            if ([indexPaths count] > 0) {
                NSArray *temp = [indexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *obj1, NSIndexPath *obj2) {
                    if (obj1.item > obj2.item) {
                        return -1;
                    }
                    if (obj1.item < obj2.item) {
                        return 1;
                    }
                    return 0;
                }];
                //
                NSMutableArray *dels = [NSMutableArray array];
                for (NSIndexPath *indexPath in temp) {
                    id item = [this.data objectAtIndex:indexPath.item-1];
                    [this.data removeObject:item];
                    [dels addObject:item];
                }
                [AppData userDeleteScheme:dels];
                [this.collectionView deleteItemsAtIndexPaths:indexPaths];
            }
            [this editTouch:this.editView];
        }
    }];
}
@end

//
@implementation SchemeCenterCell
-(void)awakeFromNib{
    [super awakeFromNib];
    if (self.infoView) {
        [self.infoView setHidden:YES];
    }
    if (self.selectView) {
        [self.selectView setHidden:YES];
    }
}
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    [self.selectView setSelected:selected];
}
@end

//
@implementation SchemeCenterCtrl
-(void)viewDidLoad{
    [super viewDidLoad];
    [self updataScheme];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectSchemeListCtrlCell:) name:@"didSelectSchemeListCtrlCell" object:nil];
    //
    if (self.onSelected) {
        [self.exitView setImage:[UIImage imageNamed:@"btn_Top_Close_nor.png"] forState:UIControlStateNormal];
        [self.exitView setImage:[UIImage imageNamed:@"btn_Top_Close_arc.png"] forState:UIControlStateHighlighted];
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //
    if (isEmpty([self.data objectForKey:@"json"])) {
        [self.data setValue:[NSMutableArray array] forKey:@"json"];
        [self performSegueWithIdentifier:@"addSegue" sender:nil];
    }
}
-(void)didSelectSchemeListCtrlCell:(NSNotification *)info{
    [self import:info.object];
    [schemeProductList setData:[self.data objectForKey:@"json"]];
    [schemeProductList reloadData];
}
-(void)import:(NSDictionary*)data{
    [self.data removeAllObjects];
    [self.data setValue:[TMJSON parse:[data objectForKey:@"json"]] forKey:@"json"];
    [self.data setValue:[data objectForKey:@"schemename"] forKey:@"schemename"];
    [self.data setValue:[data objectForKey:@"clientuuid"] forKey:@"clientuuid"];
    [self.data setValue:[data objectForKey:@"clientid"] forKey:@"clientid"];
    [self.data setValue:[data objectForKey:@"price"] forKey:@"price"];
    [self.data setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
    [self.data setValue:[data objectForKey:@"pic"] forKey:@"pic"];
    [self.data setValue:[data objectForKey:@"id"] forKey:@"id"];
    //
    [self updataScheme];
}
-(void)updataScheme{
    if (self.isViewLoaded == NO) {
        return;
    }
    //
    if ([self.data isKindOfClass:NSDictionary.class]) {
        id json = [self.data objectForKey:@"json"];
        if ([json isKindOfClass:NSString.class]) {
            json = [TMJSON parse:json];
        }
        if(json == nil){
            json = [NSMutableArray array];
        }
        [self.data setValue:json forKey:@"json"];
        //产品列表
        NSMutableArray *ids = [NSMutableArray array];
        for(id item in json){
            if([item isKindOfClass:NSMutableDictionary.class]){
                id products = [item objectForKey:@"products"];
                if(products && [products count] > 0){
                    if ([[item objectForKey:@"type"] intValue] == 3) {
                        for (id product in products) {
                            id key = [product objectForKey:@"id"];
                            if (key) {
                                [ids addObject:key];
                            }
                        }
                        break;
                    }
                }
            }
        }
        if ([ids count] > 0) {
            NSMutableDictionary *arg = [NSMutableDictionary dictionary];
            [arg setValue:[ids componentsJoinedByString:@","] forKey:@"productid"];
            //
            [self.product removeAllObjects];
            NSArray *details = [AppData productDetail:[ids componentsJoinedByString:@","]];
            [self.product addObjectsFromArray:details];
            //
            id item = [self paserProduct:self.product];
            [self replaceProduct:item];
        }
        //是否编辑
        self.tipsView.hidden = NO;
        self.listView.hidden = YES;
        for(id item in json){
            if([item isKindOfClass:NSMutableDictionary.class]){
                id products = [item objectForKey:@"products"];
                if(products && [products count] > 0){
                    self.tipsView.hidden = YES;
                    self.listView.hidden = NO;
                    break;
                }
            }
        }
        //
        [self.collectionView reloadData];
    }
}
//
-(NSMutableArray *)product{
    if (_product == nil) {
        [self setProduct:[NSMutableArray array]];
    }
    return _product;
}
-(NSMutableDictionary *)data{
    if (_data == nil) {
        [self setData:[NSMutableDictionary dictionary]];
    }
    return _data;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"didSelectCell" object:indexPath];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSMutableArray *json = [self.data objectForKey:@"json"];
    return [json count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [[self.data objectForKey:@"json"] objectAtIndex:indexPath.item];
    if ([item objectForKey:@"products"] == nil) {
        SchemeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"nullIdentifier" forIndexPath:indexPath];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"space"] lable:@"点击添加"]];
        [AppData loadImage:[item objectForKey:@"icon"] view:cell.imageView];
        [cell.eiditbtn setSelected:YES];
        return cell;
    }
    if ([[item objectForKey:@"type"] intValue] == 3) {
        SchemeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"singIdentifier" forIndexPath:indexPath];
        [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
        [cell.titieView setText:[AppData objToString:[NSString stringWithFormat:@"%@(%ld件)",[item objectForKey:@"name"],(long)[[[[self.data objectForKey:@"json"] objectAtIndex:indexPath.item] objectForKey:@"products"] count]] lable:nil]];
        //
        cell.tlIcon.image = nil;
        cell.trIcon.image = nil;
        cell.blIcon.image = nil;
        cell.brIcon.image = nil;
        NSArray *images = [NSArray arrayWithObjects:cell.tlIcon,cell.trIcon,cell.blIcon,cell.brIcon, nil];
        for (uint i=0; i<MIN([[item objectForKey:@"products"] count], 4); i++) {
            if (i < images.count) {
                UIImageView *image = [images objectAtIndex:i];
                NSDictionary *product = [[item objectForKey:@"products"] objectAtIndex:i];
                [AppData loadImage:[product objectForKey:@"pic"] view:image];
            }
        }
        return cell;
    }
    SchemeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"name"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    [cell.eiditbtn setSelected:NO];
    return cell;
}
- (void)deleteTouch:(UIButton*)sender{
    [self replaceProduct:nil];
    [self.product removeAllObjects];
    [self.collectionView reloadData];
}
-(void)replaceProduct:(id)data{
    NSMutableArray *json = [self.data objectForKey:@"json"];
    for (id item in json.reverseObjectEnumerator) {
        if ([[item objectForKey:@"type"] intValue] == 3) {
            [json removeObject:item];
        }
    }
    if (data) {
        [json addObject:data];
    }
}
-(id)getCell:(UIView*)view{
    while (view) {
        if ([view isKindOfClass:UICollectionViewCell.class]) {
            return view;
        }
        view = view.superview;
    }
    return nil;
}
//
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([sender isKindOfClass:UIButton.class]) {
        UIButton *btn = sender;
        if (btn.selected) {
            NSIndexPath *index = [self.collectionView indexPathForCell:(id)[self findCell:sender]];
            if (index) {
                [[self.data objectForKey:@"json"] removeObjectAtIndex:index.item ];
                [self.collectionView reloadData];
                [self saveScheme];
            }
            return NO;
        }
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak SchemeCenterCtrl *this = self;
    if ([self.data objectForKey:@"json"] == nil) {
        [self.data setValue:[NSMutableArray array] forKey:@"json"];
    }
    //
    if ([segue.destinationViewController isKindOfClass:ProductAssetsCtrl.class]) {
        ProductAssetsCtrl *ctrl = segue.destinationViewController;
        [ctrl setData:this.product];
        [ctrl.collectionView reloadData];
        [ctrl setOnSelected:^(id target, id result){
            [this dismissViewControllerAnimated:YES completion:^{
                id item = [this paserProduct:this.product];
                [this replaceProduct:item];
                //
                [this.collectionView reloadData];
                [this saveScheme];
            }];
        }];
        return;
    }
    //
    if ([segue.destinationViewController isKindOfClass:SchemeSelector.class]) {
        SchemeSelector *ctrl = segue.destinationViewController;
        NSIndexPath *index = [this.collectionView indexPathForCell:sender];
        if (index) {
            NSMutableArray *json = [self.data objectForKey:@"json"];
            NSMutableDictionary *item = [json objectAtIndex:index.item];
            ctrl.classids =[[item objectForKey:@"id"] integerValue];
        }
        [ctrl setOnSelected:^(id target, id result){
            if (result) {
                NSIndexPath *index = [this.collectionView indexPathForCell:sender];
                if (index) {
                    NSMutableDictionary *item = [[this.data objectForKey:@"json"] objectAtIndex:index.item];
                    if ([target isKindOfClass:SpaceEditController.class]) {
                        [item addEntriesFromDictionary:[this paserSpace:result]];
                    }
                    if ([target isKindOfClass:MatchDetailCtrl.class]) {
                        [item addEntriesFromDictionary:[this paserMatch:result]];
                    }
                }
            }
            [this dismissViewControllerAnimated:YES completion:^{
                [this.collectionView reloadData];
                [this saveScheme];
            }];
        }];
        return;
    }
    //
    if([segue.identifier isEqualToString:@"productListConstrants"]){
        IndexHomeCtrl *tabbar = (id)self.tabBarController;
        if ([tabbar isKindOfClass:IndexHomeCtrl.class]){
            [tabbar hiddenMenu];
        }
        schemeProductList = [segue destinationViewController];;
        [schemeProductList setData:[self.data objectForKey:@"json"]];
        [schemeProductList setOnSelected:^(id target, id result){
            [this dismissViewControllerAnimated:YES completion:nil];
        }];
        return;
    }
    //
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:SchemeCenterAdd.class]) {
            SchemeCenterAdd *temp = [ctrl.viewControllers firstObject];
            [temp setOnSelected:^(id target, id result){
                if (result) {
                    if ([result isKindOfClass:NSArray.class]) {
                        [[this.data objectForKey:@"json"] addObjectsFromArray:result];
                    }else{
                        if ([result isKindOfClass:NSDictionary.class]) {
                            [this.data addEntriesFromDictionary:result];
                        }
                    }
                }
                [this dismissViewControllerAnimated:YES completion:^{
                    [this.collectionView reloadData];
                    if (result) {
                        [this saveScheme];
                    }
                }];
            }];
            [temp setAppend:!isEmpty([this.data objectForKey:@"json"])];
        }
        //
        if ([[ctrl.viewControllers firstObject] isKindOfClass:SchemeProductList.class]) {
            NSIndexPath *index = [this.collectionView indexPathForCell:[self findCell:sender]];
            if (index) {
                SchemeProductList *temp = [ctrl.viewControllers firstObject];
                [temp setData:[this.data objectForKey:@"json"]];
                [temp setIndex:index.item ];
                [temp setOnSelected:^(id target, id result){
                    [this dismissViewControllerAnimated:YES completion:nil];
                }];
            }
        }
        return;
    }
    if ([segue.destinationViewController isKindOfClass:ProductCenterCtrl.class]) {
        ProductCenterCtrl *ctrl = segue.destinationViewController;
        [ctrl setOnSelected:^(id target, id result){
            if ([target isKindOfClass:ProductDetailCtrl.class]) {
                if (result) {
                    [this.product addObject:result];
                    //
                    id item = [this paserProduct:this.product];
                    [this replaceProduct:item];
                }
            }
            //
            [this dismissViewControllerAnimated:YES completion:^{
                [this.collectionView reloadData];
                [this saveScheme];
            }];
        }];
        [ctrl setType:1];
        return;
    }
    //
    if ([segue.destinationViewController isKindOfClass:SchemeSinglePopover.class]) {
        UIPopoverPresentationController *popover = (id)[segue.destinationViewController presentationController];
        if ([sender isKindOfClass:UIView.class] && [popover isKindOfClass:UIPopoverPresentationController.class]) {
            [popover setSourceRect:[(UIView*)sender bounds]];
            [popover setSourceView:(UIView*)sender];
            
        }
        SchemeSinglePopover *ctrl = segue.destinationViewController;
        id cell = [self getCell:sender];
        NSIndexPath *index = [this.collectionView indexPathForCell:cell];
        if (index) {
            NSMutableDictionary *item = [[self.data objectForKey:@"json"] objectAtIndex:index.item];
            ctrl.classids =[[item objectForKey:@"classids"] integerValue];
        }
        
        [ctrl setOnSelected:^(id target, id result){
            if ([target isKindOfClass:ProductDetailCtrl.class]) {
                if (result) {
                    [this.product addObject:result];
                    //
                    id item = [this paserProduct:this.product];
                    [this replaceProduct:item];
                }
            }else{
                //删除
                [self replaceProduct:nil];
                [self.product removeAllObjects];
                [self.collectionView reloadData];
            }
            [this dismissViewControllerAnimated:YES completion:^{
                [this.collectionView reloadData];
                [this saveScheme];
            }];
        }];
        return;
    }
    //
    if ([segue.destinationViewController isKindOfClass:SchemeCustomPopover.class]) {
        UIPopoverPresentationController *popover = (id)[segue.destinationViewController presentationController];
        if ([sender isKindOfClass:UIView.class] && [popover isKindOfClass:UIPopoverPresentationController.class]) {
            [popover setSourceRect:[(UIView*)sender bounds]];
            [popover setSourceView:(UIView*)sender];
            
        }
        //
        SchemeCustomPopover *ctrl = segue.destinationViewController;
        id cell = [self getCell:sender];
        NSIndexPath *index = [this.collectionView indexPathForCell:cell];
        if (index) {
            NSMutableDictionary *item = [[self.data objectForKey:@"json"] objectAtIndex:index.item];
            ctrl.classids =[[item objectForKey:@"classids"] integerValue];
            ctrl.type =[[item objectForKey:@"type"] intValue];
            if([[item objectForKey:@"type"] intValue] == 1){
                ctrl.str =[item objectForKey:@"name"];
                ctrl.dat = item;
            }
            if([[item objectForKey:@"type"] intValue] == 2){
                 ctrl.dat = [item objectForKey:@"source"];
            }
        }
        [ctrl setOnSelected:^(id target, id result){
            if ([target isKindOfClass:SchemeCenterAdd.class]) {
                if (result) {
                    [[this.data objectForKey:@"json"] addObjectsFromArray:result];
                }
            }
            if ([target isKindOfClass:ProductDetailCtrl.class]) {
                if (result) {
                    [this.product addObject:result];
                    //
                    id item = [this paserProduct:this.product];
                    [this replaceProduct:item];
                }
            }
            if ([target isKindOfClass:SchemeCustomPopover.class]) {
                if ([result isKindOfClass:NSIndexPath.class]) {
                    NSIndexPath *index = [this.collectionView indexPathForCell:(id)[self findCell:sender]];
                    if (index) {
                        if ([result row] == 4 && [target isKindOfClass:SchemeCustomPopover.class]) {
                            NSMutableDictionary *item = [[self.data objectForKey:@"json"] objectAtIndex:index.item];
                            NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:item];
                            [[self.data objectForKey:@"json"] addObject:temp];
                        }
                        if ([result row] == 5 && [target isKindOfClass:SchemeCustomPopover.class]) {
                            [[self.data objectForKey:@"json"] removeObjectAtIndex:index.item ];
                        }
                    }
                }
            }
            if ([target isKindOfClass:SpaceEditController.class] || [target isKindOfClass:MatchDetailCtrl.class]) {
                if (result) {
                    NSIndexPath *index = [this.collectionView indexPathForCell:(id)[self findCell:sender]];
                    if (index) {
                        NSMutableDictionary *item = [[self.data objectForKey:@"json"] objectAtIndex:index.item ];
                        if ([target isKindOfClass:SpaceEditController.class]) {
                            [item addEntriesFromDictionary:[this paserSpace:result]];
                        }
                        if ([target isKindOfClass:MatchDetailCtrl.class]) {
                            [item addEntriesFromDictionary:[this paserMatch:result]];
                        }
                    }
                }
            }
            [this dismissViewControllerAnimated:YES completion:^{
                [this.collectionView reloadData];
                [this saveScheme];
            }];
        }];
        return;
    }
}
- (id)findCell:(UIView*)view{
    while (view) {
        if ([view isKindOfClass:UICollectionViewCell.class]) {
            return view;
        }
        view = view.superview;
    }
    return nil;
}
//
- (void)saveScheme{
    __weak SchemeCenterCtrl *this = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id picdata = [this.data objectForKey:@"picdata"];
        if (picdata == nil) {
            NSDictionary *item = [[this.data objectForKey:@"json"] firstObject];
            if ([item isKindOfClass:NSDictionary.class] && [item objectForKey:@"pic"]) {
                id pic = [item objectForKey:@"pic"];
                if (NO == [[self.data  objectForKey:@"pic"] isEqualToString:pic]) {
                    NSString *url = [AppData getPath:pic];
                    TMLoader *loader = [TMLoader load:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:nil cache:2];
                    [this.data setValue:[UIImage imageWithData:loader.data] forKey:@"picdata"];
                    [this.data setValue:pic forKey:@"pic"];
                }
            }
        }
        float total=0.00;
        id item=[this.data objectForKey:@"json"];
        for(int i=0;i<[item count];i++){
            id tp = [[item objectAtIndex:i] objectForKey:@"price"];
            total += [tp floatValue];
        }
        //
        NSMutableArray *json = [NSMutableArray array];
        NSMutableArray *items = [this.data objectForKey:@"json"];
        for (id item in items) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:item];
            if (dic) {
                [dic setValue:nil forKey:@"source"];
                [json addObject:dic];
            }
        }
        NSMutableDictionary *post = [NSMutableDictionary dictionaryWithDictionary:this.data];
        [post setValue:json forKey:@"json"];
        //
        [AppData userEditScheme:post bitmap:nil];
        [this.data setValue:[post objectForKey:@"id"] forKey:@"id"];
        [this.data setValue:[post objectForKey:@"uuid"] forKey:@"uuid"];
        [this.data setValue:[NSNumber numberWithFloat:total] forKey:@"price"];
        //
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:this.view animated:YES];
        });
    });
    //
    [self.tipsView setHidden:NO];
    [self.listView setHidden:YES];
    id json = [self.data objectForKey:@"json"];
    for(id item in json){
        if([item isKindOfClass:NSMutableDictionary.class]){
            if([[item objectForKey:@"products"] count] > 0){
                [schemeProductList setData:json];
                [schemeProductList reloadData];
                [self.tipsView setHidden:YES];
                [self.listView setHidden:NO];
                return;
            }
        }
    }
}

-(IBAction)exitTouch:(UIButton *)sender {
    if (self.onSelected) {
        self.onSelected(self, self.data);
    }else{
        IndexHomeCtrl *tabbar = (id)self.splitViewController;
        if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
            [tabbar showMenu];
        }
    }
}
//schemeType[1:空间,2:搭配,3:单品]
-(id)paserSpace:(id)data{
    NSMutableArray *products = [NSMutableArray array];
    for (NSDictionary *all in [data objectForKey:@"products"]) {
        for (id val in all.allValues) {
            if ([val isKindOfClass:NSDictionary.class]) {
                id hardpacked = nil;
                id name = [val objectForKey:@"name"];
                if ([name isEqualToString:@"软装"]) {
                    hardpacked = [NSNumber numberWithInt:0];
                }else{
                    hardpacked = [NSNumber numberWithInt:1];
                }
                //
                for (id dat in [val objectForKey:@"data"]) {
                    for (id cls in [dat objectForKey:@"class_product"]) {
                        id pro = [cls objectForKey:@"product"];
                        id subs = [pro objectForKey:@"sub"];
                        if (subs && [subs count] > 0) {
                            for (id sub in subs) {
                                NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
                                [tmp setValue:[val objectForKey:@"name"] forKey:@"section"];
                                [tmp setValue:[val objectForKey:@"suitid"] forKey:@"suitid"];
                                [tmp setValue:[sub objectForKey:@"productcount"] forKey:@"productcount"];
                                [tmp setValue:[pro objectForKey:@"thumb400_jpg"] forKey:@"pic"];
                                [tmp setValue:[sub objectForKey:@"id"] forKey:@"id"];
                                [tmp setValue:hardpacked forKey:@"hardpacked"];
                                [products addObject:tmp];
                            }
                        }else{
                            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
                            [tmp setValue:[val objectForKey:@"name"] forKey:@"section"];
                            [tmp setValue:[val objectForKey:@"suitid"] forKey:@"suitid"];
                            [tmp setValue:[pro objectForKey:@"productcount"] forKey:@"productcount"];
                            [tmp setValue:[pro objectForKey:@"thumb400_jpg"] forKey:@"pic"];
                            [tmp setValue:[pro objectForKey:@"id"] forKey:@"id"];
                            [tmp setValue:hardpacked forKey:@"hardpacked"];
                            [products addObject:tmp];
                        }
                        //只取第一个
                        break;
                    }
                }
            }
        }
    }
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:[data objectForKey:@"suitname"] forKey:@"name"];
    [temp setValue:[data objectForKey:@"price"] forKey:@"price"];
    [temp setValue:[data objectForKey:@"pic"] forKey:@"pic"];
    [temp setValue:[data objectForKey:@"id"] forKey:@"id"];
    [temp setValue:[data objectForKey:@"classids"] forKey:@"classids"];
    [temp setValue:products forKey:@"products"];
    [temp setValue:data forKey:@"source"];
    [temp setValue:@"1" forKey:@"type"];
    return temp;
}
-(id)paserMatch:(id)data{
    NSMutableArray *products = [NSMutableArray array];
    //
    NSDictionary *json = [TMJSON parse:[data objectForKey:@"json"]];
    if (json) {
        NSMutableDictionary *count = [NSMutableDictionary dictionary];
        NSMutableDictionary *image = [NSMutableDictionary dictionary];
        for (NSDictionary *layer in [json objectForKey:@"layers"]) {
            id iid = [layer objectForKey:@"identifier"];
            [image setValue:[layer objectForKey:@"image"] forKey:iid];
            //
            id num = [count objectForKey:iid];
            if (num) {
                [count setValue:[NSNumber numberWithInt:[num intValue] + 1] forKey:iid];
            }else{
                [count setValue:[NSNumber numberWithInt:1] forKey:iid];
            }
        }
        for (id iid in count.allKeys) {
            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
            [tmp setValue:[count objectForKey:iid] forKey:@"productcount"];
            [tmp setValue:[image objectForKey:iid] forKey:@"pic"];
            [tmp setValue:iid forKey:@"id"];
            [products addObject:tmp];
        }
    }
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:[data objectForKey:@"matchname"] forKey:@"name"];
    [temp setValue:[data objectForKey:@"price"] forKey:@"price"];
    [temp setValue:[data objectForKey:@"pic"] forKey:@"pic"];
    [temp setValue:[data objectForKey:@"id"] forKey:@"id"];
    [temp setValue:products forKey:@"products"];
    [temp setValue:data forKey:@"source"];
    [temp setValue:@"2" forKey:@"type"];
    return temp;
}
-(id)paserProduct:(id)data{
    if ([data count] > 0) {
        CGFloat price = 0;
        NSMutableArray *products = [NSMutableArray array];
        NSMutableDictionary *count = [NSMutableDictionary dictionary];
        NSMutableDictionary *image = [NSMutableDictionary dictionary];
        for (NSDictionary *item in data) {
            id iid = [item objectForKey:@"id"];
            [image setValue:[item objectForKey:@"thumb400_jpg"] forKey:iid];
            //
            id num = [count objectForKey:iid];
            if (num) {
                [count setValue:[NSNumber numberWithInt:[num intValue] + 1] forKey:iid];
            }else{
                [count setValue:[NSNumber numberWithInt:1] forKey:iid];
            }
            //
            price += [[item objectForKey:@"price"] floatValue];
        }
        for (id iid in count.allKeys) {
            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
            [tmp setValue:[count objectForKey:iid] forKey:@"productcount"];
            [tmp setValue:[image objectForKey:iid] forKey:@"pic"];
            [tmp setValue:iid forKey:@"id"];
            [products addObject:tmp];
        }
        //
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[NSString stringWithFormat:@"%f",price] forKey:@"price"];
        [temp setValue:products forKey:@"products"];
        [temp setValue:@"单品" forKey:@"space"];
        [temp setValue:@"单品" forKey:@"name"];
        [temp setValue:data forKey:@"source"];
        [temp setValue:@"3" forKey:@"type"];
        return temp;
    }
    return nil;
}
@end